import sys
import matplotlib
from PyQt5 import QtCore

from PyQt5.QtGui import QPixmap
from matplotlib import rcParams
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.Qt import QMainwindow
import connector.DatabaseDriver
import dao.StatisticsDao
import matplotlib.pyplot as plt
plt.rcParams['axes.unicode_minus']= False
cn_font = matplotlib.font_manager.FontProperties(fname="./font/SourceHanSansSc-Light.otf")
class statisticPage(QMainwindow):
    def __init__(self):
        super( statisticPage,self).__init__()
        self.driver = connector.driver.DatabaseDriver()
        self.setupUi(self)
        self.render_img()
        self.show()

def closeEvent(self, a0):
    self.driver.close()
def setupui(self, Form):
    Form.setObjectName("statistic")
    Form.resize(900, 700)
    Form.setFixedSize(900, 700)
    self.hLayoutwidget = QtWidgets.Qwidget(parent=Form)
    self.hLayoutWidget.setGeometry(QtCore.QRect(0,0,900,700))
    self.hLayoutWidget.setObjectName("gridLayoutWidget")
    self.hLayout =QtWidgets.QHBoxLayout(self.hLayoutWidget)
    self.img = QtWidgets.QLabel(parent=self.hLayoutWidget)
    self.img.setObjectName("img")
    self.img.setFixedwidth(900)
    self.img.setFixedHeight(700)
    self.hLayout.addwidget(self.img)
    self.retranslateUi(Form)
    QtCore.QMeta0bject.connectSlotsByName(Form)
def retranslateUi(self, Form):
    _translate = QtCore.QCoreApplication.translate
    Form.setWindowTitle(_translate("Form", "Form"))
    self.img.setText(_translate("Form", "TextLabel"))
def render_img(self):
    global cn_font
    plt.figure(figsize=(5, 3.8), dpi=160)
    data: list = dao.StatisticsDao.book_count_by_type(self.driver)
    data: list = dao.StatisticsDao.book_count_by_type(self.driver)
    values = []
    for book_type, book_count in data:
        dao.categories.append(book_type.strip())
        values.append(book_count)
    print(dao.categories, values)


    plt.bar(dao.categories, values)
    plt.xticks(fontproperties=cn_font)
    plt.xlabel("分类",fontproperties = cn_font)
    plt.ylabel("个数",fontproperties = cn_font)
    plt.title("各类别的图书数量",fontproperties = cn_font)
    plt.savefig("plot.png")

    pixmap = QPixmap("plot.png")
    self.img.setPixmap(pixmap)







